package com.wanxi.servlet.user;

import com.alibaba.fastjson.JSONObject;
import com.wanxi.dto.ResultDto;
import com.wanxi.model.UserModel;
import com.wanxi.service.UserService;
import com.wanxi.service.impl.UserServiceImpl;
import com.wanxi.util.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/back/user/add")
public class UserAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1.乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
//        2.得到前端的值
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String birthday = req.getParameter("birthday");
        String hobby = req.getParameter("hobby");
        String sex = req.getParameter("sex");
        String enable = req.getParameter("enable");
        String age = req.getParameter("age");
//        3.封装到model
        UserModel model = UserModel.builder()
                .username(username)
                .password(password)
                .email(email)
                .sex(sex)
                .age(Tool.strToInt(age))
                .phone(phone)
                .address(address)
                .birthday(Tool.strToBirthday(birthday))
                .hobby(hobby)
                .enable(Tool.strToInt(enable))
                .build();

//        4.调用服务逻辑层
        UserService userService = new UserServiceImpl();
        String result = userService.add(model);
//        UserDto userDto = userService.findById(model);
//        List<UserDto> list = userService.findAll(model);
//        5.将返回的数据响应给前端
//        以后全部以json对象的格式传递给前端{"age":13,"username":"aaaa"}
//        所以，需要将字符串放入对象,然后用统一格式进行输出
// 响应给前端的值不应该将数据库里面所有的值给前端，比如密码
//        DTO响应给前端的对象,model就是前端给后端的对象
//        引入第三方组件：fastjson
//        JSONObject.toJSONString(list);
//        ResultDto.builder()
//                .msg(result)
//                .build();
//
//        ResultDto.builder()
//                .data(userDto)
//                .build();
//
//        ResultDto.builder()
//                .data(list)
//                .build();
//        ResultDto.builder()
//                .count(1)
//                .build();
        resp.getWriter().println(JSONObject.toJSONString(ResultDto.getInstance(result)));
//        resp.getWriter().println(ResultDto.getInstance(1));
//        resp.getWriter().println(ResultDto.getInstance(model));


    }


}
